<template>
  <section class="todoapp">
	<header class="header">
		<h1>todos</h1>
		<input class="new-todo" @keyup.enter="addTodo" v-model.trim="todoname" placeholder="What needs to be done?" autofocus>
	</header>
    
	<section class="main">
		<input id="toggle-all" class="toggle-all" type="checkbox" v-model="ischeckAll">
		<label for="toggle-all">Mark all as complete</label>
		<ul class="todo-list">
			<li :class="{completed:item.flag}" v-for="item in list" :key="item.id">
				<div class="view">
					<input class="toggle" type="checkbox" v-model="item.flag">
					<label>{{item.name}}</label>
					<button class="destroy" @click="delbtn(item.id)"></button>
				</div>
				<input class="edit" value="Create a TodoMVC template">
			</li>
		</ul>
	</section>
    
	<footer class="footer">
		<span class="todo-count"><strong>{{todoLength}}</strong> item left</span>
		<ul class="filters">
			<li>
				<a class="selected" href="#/">All</a>
			</li>
			<li>
				<a href="#/active">Active</a>
			</li>
			<li>
				<a href="#/completed">Completed</a>
			</li>
		</ul>
		<button class="clear-completed">Clear completed</button>
	</footer>
</section>
</template>

<script>
import { toRefs,reactive, computed, watch } from 'vue'
export default {
    setup(){
        const state = reactive({
            
            list:JSON.parse(localStorage.getItem('todoList')) || [
                {id:1, name:'学习',flag:true},
                {id:2, name:'睡觉',flag:false},
                {id:3, name:'打豆豆',flag:false}
            ],
            todoname:''
        })

        // 删除功能
        const delbtn = (id) => {
          state.list = state.list.filter((item)=> item.id !== id)
        }

        // 添加
        const addTodo = () => {
            // 判断内容为空就返回提示用户
            if(!state.todoname) return alert('请输入内容')

            // 对象
            const obj = {
              id:state.list.length+1,
              name:state.todoname,
              flag:false
            }
          state.list = [obj,...state.list]
            state.todoname = ''
        }

        // 长度
        const todoLength = computed(() => {
          return state.list.filter(item=>item.flag === false).length
        })


        // 
        const ischeckAll = computed({
            get: ()=> {
                return state.list.every(item => item.flag === true)
            },
            set: (val)=>{
                console.log(val);
                state.list.forEach(item=> item.flag = val)
            }
        })

        watch(()=>state.list, ()=>{
            localStorage.setItem('todoList', JSON.stringify(state.list))
        },{deep:true})

        return {...toRefs(state), delbtn, addTodo, todoLength,ischeckAll}

        
}
}
</script>
